<?php
/**
 * NOTICE OF LICENSE
 *
 * This source file is subject to the  Academic Free License (AFL 3.0)
 * that is available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to support@zprofess.com so we can send you a copy immediately.
 *
 * @category   	Prestashop module
 * @package		Help Desk
 * @version 	1.0
 * @author 		Kurosaki <kurosaki@zprofess.com>
 * @copyright   Copyright (c) 2012 ZPROFESS. (http://zprofess.com)
 * @license    	http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

include_once(dirname(__FILE__).'/../../classes/AdminTab.php');
include_once(dirname(__FILE__).'/classes/ZticketObject.php');
include_once(dirname(__FILE__).'/classes/ZticketContentObject.php');
include_once(dirname(__FILE__).'/classes/ZdepartmentObject.php');
include_once(dirname(__FILE__).'/classes/ZpriorityObject.php');
include_once(dirname(__FILE__).'/classes/ZstatusObject.php');
include_once(dirname(__FILE__).'/classes/ZratingObject.php');

require_once(dirname(__FILE__).'/lib/zprofess/ZhelpdeskadminTab.php');

class ZadminTicket extends ZhelpdeskadminTab
{
	public $employee;
	/**
	 * 
	 * Sole constructor
	 */ 
	public function  __construct()
	{
		global $cookie;
		
		$this->edit = true;
		$this->delete = true;
		$this->lang = false;
		
		$this->table = 'zhelpdesk_ticket';
		$this->className = 'ZTicketObject';
		
		$this->_select = '
        zdl.`name`,
        CONCAT_WS(" ", ze.`firstname`, ze.`lastname`) as name_staff,
        ztsl.`status`,
        zts.`backgroud_color` as stt_bgcolor,
        zts.`text_color` as stt_text_color,
        ztpl.`priority` ,
        ztp.`backgroud_color` as pri_bgcolor,
        ztp.`text_color` as pri_text_color
        ';
 		// join department, staff(employee), status, priority
		$this->_join = '
		LEFT JOIN `' . _DB_PREFIX_ . 'zhelpdesk_department` as zd ON (zd.`id_zhelpdesk_department` = a.`id_zhelpdesk_department`)
        LEFT JOIN `' . _DB_PREFIX_ . 'zhelpdesk_department_lang` as zdl ON (zdl.`id_zhelpdesk_department` = zd.`id_zhelpdesk_department` AND zdl.`id_lang` = ' . (int) $cookie->id_lang .')
        LEFT JOIN `' . _DB_PREFIX_ . 'employee` as ze ON (ze.`id_employee` = a.`id_staff`)
        
        LEFT JOIN `' . _DB_PREFIX_ . 'zhelpdesk_ticket_status` as zts ON (zts.`id_zhelpdesk_ticket_status` = a.`id_zhelpdesk_ticket_status`)
        LEFT JOIN `' . _DB_PREFIX_ . 'zhelpdesk_ticket_status_lang` as ztsl ON (ztsl.`id_zhelpdesk_ticket_status` = zts.`id_zhelpdesk_ticket_status` AND ztsl.`id_lang` = ' . (int) $cookie->id_lang .')
        
        LEFT JOIN `' . _DB_PREFIX_ . 'zhelpdesk_ticket_priority` as ztp ON (ztp.`id_zhelpdesk_ticket_priority` = a.`id_zhelpdesk_ticket_priority`)
        LEFT JOIN `' . _DB_PREFIX_ . 'zhelpdesk_ticket_priority_lang` as ztpl ON (ztpl.`id_zhelpdesk_ticket_priority` = ztp.`id_zhelpdesk_ticket_priority` AND ztpl.`id_lang` = ' . (int) $cookie->id_lang .')
        ';
		
		$this->employee = new Employee($cookie->id_employee);
		if ($this->employee->id_profile != 1 )
			$this->_where = 'AND a.`id_staff` = '.$cookie->id_employee.' OR zd.`id_moderator` = '.$cookie->id_employee.'';
		
		$this->fieldsDisplay = array(							
			'id_zhelpdesk_ticket' => array('title' => $this->l('ID'), 'align' => 'center', 'width' => 25 ),
			'ticket_code' => array('title' => $this->l('Ticket'), 'align' => 'center', 'width' => 50 ),
			'subject' => array('title' => $this->l('Subject'),'width' => 120 ,'align' => 'center'),
			'date_upd' => array('title' => $this->l('Last update'), 'width' => 30, 'type' => 'datetime', 'align' => 'right'),
//			'name_customer' => array('title' => $this->l('Name'),'width' => 80 , 'align' => 'center', 'maxlength' => 50),
			'email_customer' => array('title' => $this->l('Email'),'width' => 100,'align' => 'center', 'maxlength' => 200),		
			'name' => array('title' => $this->l('Department'),'width' => 80, 'align' => 'center'),
			'name_staff' => array('title' => $this->l('Staff'), 'width' => 80, 'align' => 'center'),
			'priority' => array('title' => $this->l('Priority'), 'align' => 'center', 'width' => 50),	
			'status' => array('title' => $this->l('Status'), 'align' => 'center', 'width' => 50),
        );
        
        
		parent::__construct();
	}
	
	/**
	 * 
	 * override AdminTab->displayListContent: edit link edit
	 * @param string $token
	 */
	public function displayListContent($token = NULL)
	{
		/* Display results in a table
		 *
		 * align  : determine value alignment
		 * prefix : displayed before value
		 * suffix : displayed after value
		 * image  : object image
		 * icon   : icon determined by values
		 * active : allow to toggle status
		 */

		global $currentIndex, $cookie;
		$currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));

		$id_category = 1; // default categ

		$irow = 0;
		if ($this->_list AND isset($this->fieldsDisplay['position']))
		{
			$positions = array_map(create_function('$elem', 'return (int)($elem[\'position\']);'), $this->_list);
			sort($positions);
		}
		if ($this->_list)
		{
			$isCms = false;
			if (preg_match('/cms/Ui', $this->identifier))
				$isCms = true;
			$keyToGet = 'id_'.($isCms ? 'cms_' : '').'category'.(in_array($this->identifier, array('id_category', 'id_cms_category')) ? '_parent' : '');
			foreach ($this->_list AS $tr)
			{
				$id = $tr[$this->identifier];
				echo '<tr id="tr_1_'.$tr['id_zhelpdesk_ticket'].'" '.($irow++ % 2 ? ' class="alt_row"' : '').' '.((isset($tr['color']) AND $this->colorOnBackground) ? 'style="background-color: '.$tr['color'].'"' : '').'>
							<td class="center">';
				if ($this->delete AND (!isset($this->_listSkipDelete) OR !in_array($id, $this->_listSkipDelete)))
					echo '<input type="checkbox" name="'.$this->table.'Box[]" value="'.$id.'" class="noborder" />';
				echo '</td>';
				foreach ($this->fieldsDisplay AS $key => $params)
				{
					$tmp = explode('!', $key);
					$key = isset($tmp[1]) ? $tmp[1] : $tmp[0];
					echo '
					<td '.(isset($params['position']) ? ' id="td_'.(isset($id_category) AND $id_category ? $id_category : 0).'_'.$id.'"' : '').' class="'.((!isset($this->noLink) OR !$this->noLink) ? 'pointer' : '').((isset($params['position']) AND $this->_orderBy == 'position')? ' dragHandle' : ''). (isset($params['align']) ? ' '.$params['align'] : '').'" ';
					if (!isset($params['position']) AND (!isset($this->noLink) OR !$this->noLink))
						echo ' onclick="document.location = \''.$currentIndex.'&'.$this->identifier.'='.$id.($this->view? '&view' : '&update').$this->table.'&id_tab=1&token='.($token!=NULL ? $token : $this->token).'\'">'.(isset($params['prefix']) ? $params['prefix'] : '');
					else
						echo '>';
					if (isset($params['active']) AND isset($tr[$key]))
						$this->_displayEnableLink($token, $id, $tr[$key], $params['active'], Tools::getValue('id_category'), Tools::getValue('id_product'));
					elseif (isset($params['activeVisu']) AND isset($tr[$key]))
						echo '<img src="../img/admin/'.($tr[$key] ? 'enabled.gif' : 'disabled.gif').'"
						alt="'.($tr[$key] ? $this->l('Enabled') : $this->l('Disabled')).'" title="'.($tr[$key] ? $this->l('Enabled') : $this->l('Disabled')).'" />';
					elseif (isset($params['position']))
					{
						if ($this->_orderBy == 'position' AND $this->_orderWay != 'DESC')
						{
							echo '<a'.(!($tr[$key] != $positions[sizeof($positions) - 1]) ? ' style="display: none;"' : '').' href="'.$currentIndex.
									'&'.$keyToGet.'='.(int)($id_category).'&'.$this->identifiersDnd[$this->identifier].'='.$id.'
									&way=1&position='.(int)($tr['position'] + 1).'&token='.($token!=NULL ? $token : $this->token).'">
									<img src="../img/admin/'.($this->_orderWay == 'ASC' ? 'down' : 'up').'.gif"
									alt="'.$this->l('Down').'" title="'.$this->l('Down').'" /></a>';

							echo '<a'.(!($tr[$key] != $positions[0]) ? ' style="display: none;"' : '').' href="'.$currentIndex.
									'&'.$keyToGet.'='.(int)($id_category).'&'.$this->identifiersDnd[$this->identifier].'='.$id.'
									&way=0&position='.(int)($tr['position'] - 1).'&token='.($token!=NULL ? $token : $this->token).'">
									<img src="../img/admin/'.($this->_orderWay == 'ASC' ? 'up' : 'down').'.gif"
									alt="'.$this->l('Up').'" title="'.$this->l('Up').'" /></a>';						}
						else
							echo (int)($tr[$key] + 1);
					}
					elseif (isset($params['image']))
					{
						// item_id is the product id in a product image context, else it is the image id.
						$item_id = isset($params['image_id']) ? $tr[$params['image_id']] : $id;
						// If it's a product image
						if (isset($tr['id_image']))
						{
							$image = new Image((int)$tr['id_image']);
							$path_to_image = _PS_IMG_DIR_.$params['image'].'/'.$image->getExistingImgPath().'.'.$this->imageType;
						}else
							$path_to_image = _PS_IMG_DIR_.$params['image'].'/'.$item_id.(isset($tr['id_image']) ? '-'.(int)($tr['id_image']) : '').'.'.$this->imageType;

						echo cacheImage($path_to_image, $this->table.'_mini_'.$item_id.'.'.$this->imageType, 45, $this->imageType);
					}
					elseif (isset($params['icon']) AND (isset($params['icon'][$tr[$key]]) OR isset($params['icon']['default'])))
						echo '<img src="../img/admin/'.(isset($params['icon'][$tr[$key]]) ? $params['icon'][$tr[$key]] : $params['icon']['default'].'" alt="'.$tr[$key]).'" title="'.$tr[$key].'" />';
					elseif (isset($params['price']))
						echo Tools::displayPrice($tr[$key], (isset($params['currency']) ? Currency::getCurrencyInstance((int)($tr['id_currency'])) : $currency), false);
					elseif (isset($params['float']))
						echo rtrim(rtrim($tr[$key], '0'), '.');
					elseif (isset($params['type']) AND $params['type'] == 'date')
						echo Tools::displayDate($tr[$key], (int)$cookie->id_lang);
					elseif (isset($params['type']) AND $params['type'] == 'datetime')
						echo Tools::displayDate($tr[$key], (int)$cookie->id_lang, true);
					elseif (isset($tr[$key]))
					{
						$echo = ($key == 'price' ? round($tr[$key], 2) : isset($params['maxlength']) ? Tools::substr($tr[$key], 0, $params['maxlength']).'...' : $tr[$key]);
						echo isset($params['callback']) ? call_user_func_array(array($this->className, $params['callback']), array($echo, $tr)) : $echo;
					}
					else
						echo '--';

					echo (isset($params['suffix']) ? $params['suffix'] : '').
					'</td>';
				}

				if ($this->edit OR $this->delete OR ($this->view AND $this->view !== 'noActionColumn'))
				{
					echo '<td class="center" style="white-space: nowrap;">';
					if ($this->view)
						$this->_displayViewLink($token, $id);
					if ($this->edit)
						$this->_displayEditLink($token, $id);
					if ($this->delete AND (!isset($this->_listSkipDelete) OR !in_array($id, $this->_listSkipDelete)))
						$this->_displayDeleteLink($token, $id);
					if ($this->duplicate)
						$this->_displayDuplicate($token, $id);
					echo '</td>';
				}
				echo '</tr>';
			}
		}
	}
	
	/**
	 * 
	 * return link edit id tab =1 (Ticket thread tab)
	 * @param string $token
	 * @param integer $id
	 */
	protected function _displayEditLink($token = NULL, $id)
	{
		global $currentIndex;

		$_cacheLang['Edit'] = $this->l('Edit');

		echo '
			<a href="'.$currentIndex.'&'.$this->identifier.'='.$id.'&update'.$this->table.'&id_tab=1&token='.($token!=NULL ? $token : $this->token).'">
			<img src="../img/admin/edit.gif" alt="" title="'.$_cacheLang['Edit'].'" /></a>';
	}
	
	/**
	 * @see AdminTabs->postProcess();
	 * 
	 * Manage page processing
	 *
	 * @global string $currentIndex Current URL in order to keep current Tab
	 */
	public function postProcess()
	{
		global $currentIndex, $cookie;	
		$token = Tools::getValue('token') ? Tools::getValue('token') : $this->token;
		
		// reply ticket
		if (Tools::getValue('submitReplyContent'))
		{
			$date = date("Y-m-d h:i:s");
			$object = $this->loadObject();
			$objTicketContent = new ZTicketContentObject();
			if (isset($_POST['content']) AND Tools::getValue('content')=='')
				$this->_errors[] = Tools::displayError('Invalid Content ');
			$target = dirname(__FILE__).'/fileattach/';
			$file = $_FILES['attach']['name'];
			if (isset($file) AND $file!='')
				if($_FILES["attach"]["size"] >= 2097152)
				{
					$this->_errors[] = 'File upload to maxsize';
				}else {
					if(move_uploaded_file($_FILES['attach']['tmp_name'],$target.$file)==true)
						$objTicketContent->attached_files = $file;
					else 
						$this->_errors[] = 'File not upload';
				}
			
			$objTicketContent->id_zhelpdesk_ticket = Tools::getValue('id_zhelpdesk_ticket');
//			$objTicketContent->id_staff = Tools::getValue('id_staff');
			$objTicketContent->id_staff = $cookie->id_employee;
			$objTicketContent->content = Tools::getValue('content');
			
			if (!sizeof($this->_errors)){
				if (!$objTicketContent->add())
					$this->_errors[] = Tools::displayError('An error occurred while creating object.').' <b> zhelpdesk_ticket_content ('.mysql_error().')</b>';
                else{
                	ZTicketObject::updateTicketTime(Tools::getValue('id_zhelpdesk_ticket'), $date);
                    ZTicketObject::setTicketStatus(Tools::getValue('id_zhelpdesk_ticket'), 3);
					                    
                    /* ----getway send mail when staff reply ticket to customer------------- */
					$textbody = Configuration::get('UD_TICKET_TEMPLATE_FOR_CUSTOMER',Configuration::get('PS_LANG_DEFAULT'));
					
					if ($textbody == '')
						$textbody = '<p>Thank you for using our position, this is the reply mail content<p></p>{content}</p><p>Please reply to this email within 24 hours</p>';
					
					$words = array (
						'{content}' => Tools::getValue('content')
					);
					
					$rs = ZticketObject::sendMailTo ($object->email_customer,$object->name_customer,$object->subject,$textbody,$words);
					/* ----getway send mail when staff reply ticket to customer------------- */
                    
                    /* Riderect reply ticket form  */
                    Tools::redirectAdmin($currentIndex.'&'.$this->identifier.'='.Tools::getValue('id_zhelpdesk_ticket').'&conf=4&update'.$this->table.'&id_tab=1&token='.$token);
                }
			}else 
				$_GET['id_tab'] = 1;
		}
		
		// creat or update object 
		if(Tools::isSubmit('submitAdd'.$this->table))
		{
			if (isset($_POST['id_zhelpdesk_ticket']))
				$object = $this->loadObject();
			
			if (isset($_POST['email_customer']) AND empty($_POST['email_customer'])){
				$this->_errors[] = Tools::displayError('Invalid e-mail or Name');
			}elseif (Validate::isEmail($email = Tools::getValue('email_customer')))
			{
				if (Customer::customerExists($email))
				{
					$objCustomer = new Customer();
					$customer = $objCustomer->getByEmail($email);
					$_POST['name_customer'] = $customer->firstname.' '.$customer->lastname;
				}else{
					$this->_errors[] = Tools::displayError('E-mail customer is not exists ');
				}
			}else {
				
			}
			
			if (isset($_POST['id_zhelpdesk_department']) AND Tools::getValue('id_zhelpdesk_department')==0)
				$this->_errors[] = Tools::displayError('Please select Department ');
				
			if (isset($_POST['subject']) AND Tools::getValue('subject')=='')
				$this->_errors[] = Tools::displayError('Invalid subject ');
			if (isset($_POST['content']) AND Tools::getValue('content')=='')
				$this->_errors[] = Tools::displayError('Invalid Content ');
			if (isset($_POST['id_staff']) AND Tools::getValue('id_staff')=='')
				$this->_errors[] = Tools::displayError('Please choose staff!');
			
			/* creat ticket code */
			$code = ZTicketObject::genCode(8);
			while (ZTicketObject::testSameCode($code)!=0) {
				$code = ZTicketObject::genCode(8);				
			}
			$_POST['ticket_code'] =  $code;
			
			if (isset($_POST['id_zhelpdesk_ticket']) AND $object->id_staff != $_POST['id_staff']) {
				$_POST['change_staff'] = 1;
			}
			
		}
		parent::postProcess();
		
//		if (Tools::isSubmit('submitAdd'.$this->table) AND sizeof($this->_errors)) {
//			if (!isset($_POST['id_zhelpdesk_ticket'])){
//				/*************** Send mail to staff when creat new ticket for staff  ***********************/
//				$employee = new EmployeeCore($_POST['id_staff']);
//				$department = new ZdepartmentObject($_POST['id_zhelpdesk_department']);
//				// mode is user creat or moderetor department
//				$employee_moderator = new EmployeeCore($department->id_moderator);
//				$textbody = Configuration::get('ASSIGNED_TICKET_TEMPLATE',Configuration::get('PS_LANG_DEFAULT'));
//				if ($textbody == '')
//					$textbody = '<p>Hi {name_staff}, you\'ve been assigned to a ticket to {name_moderator} processor</p><p>Ticket is sent from the client name {name_customer}, email {email_customer}</p><p>Subject {subject}</p><p>Please reply to this email within 24 hours</p>';
//					
//				$words = array (
//					'{name_staff}' => $employee->firstname." ".$employee->lastname,
//					'{name_moderator}' => $employee_moderator->firstname." ".$employee_moderator->lastname,
//					'{name_customer}' => (isset($_POST['name_customer']) ? $_POST['name_customer'] : $_POST['email_customer']),
//					'{email_customer}' => $_POST['email_customer'],
//					'{subject}' => $_POST['subject'],
//				);
//				$rs = ZticketObject::sendMailTo ($employee->email,$employee->firstname,"Assigned: ".$_POST['subject'],$textbody,$words);
//				/*************** Send mail to staff when creat new ticket for staff  ***********************/
//			}
//			
//			if (isset($_POST['id_zhelpdesk_ticket']) AND $object->id_staff != $_POST['id_staff']) {
//				/*************** Send mail to staff when change staff ***********************/
//				$employee = new EmployeeCore($_POST['id_staff']);
//				$department = new ZdepartmentObject($object->id_zhelpdesk_department);
//				$employee_moderator = new EmployeeCore($department->id_moderator);
//				$textbody = Configuration::get('ASSIGNED_TICKET_TEMPLATE',Configuration::get('PS_LANG_DEFAULT'));
//				if ($textbody == '')
//					$textbody = '<p>Hi {name_staff}, you\'ve been assigned to a ticket to {name_moderator} processor</p><p>Ticket is sent from the client name {name_customer}, email {email_customer}</p><p>Subject {subject}</p><p>Please reply to this email within 24 hours</p>';
//					
//				$words = array (
//					'{name_staff}' => $employee->firstname." ".$employee->lastname,
//					'{name_moderator}' => $employee_moderator->firstname." ".$employee_moderator->lastname,
//					'{name_customer}' => $object->name_customer,
//					'{email_customer}' => $object->email_customer,
//					'{subject}' => $object->subject,
//				);
//				$rs = ZticketObject::sendMailTo ($employee->email,$employee->firstname,"Assigned: ".$object->subject,$textbody,$words);
//				/*************** Send mail to staff ***********************/
//			}
//		}
	}
	
	
	
	
	/**
	 * 
	 * @see AdminTabs->displayForm()
	 * @param $isMainTab
	 */
	public function displayForm($isMainTab = true)
	{		
	    global $currentIndex, $cookie;
        parent::displayForm();
        $object = new $this->className();
        if (!($obj = $this->loadObject(true)))
            return;
        echo $this->loadTinyMCE();
        
        echo '
            <script type="text/javascript">
                var pos_select = '.(($tab = Tools::getValue('id_tab')) ? $tab : '0').';
            </script>
            <script src="../js/tabpane.js" type="text/javascript"></script>
            <link type="text/css" rel="stylesheet" href="../css/tabpane.css" />
               ';
        echo '
              <div class="tab-pane" id="tabPane1">
             ';
        $this->displayInformationTab($obj);
        if ($obj->id OR Tools::getValue('id_zhelpdesk_ticket'))
        	$this->displayContentTab($obj);
        echo '
	                <script type="text/javascript">
	                    function loadTab(id) {};
	                </script>
               </div> 
               <div class="clear">&nbsp;</div>         
            
           ';
        
       
	}
	
	/**
	 * 
	 * Information tab ticket
	 * @param $obj
	 * 
	 * @return html
	 */
	public function displayInformationTab($obj){
        global $currentIndex, $cookie;
        
        $department = ZDepartmentObject::getAllDepartMent($cookie->id_lang);
        $priority = ZpriorityObject::getSelectPriority();
        $status = ZstatusObject::getAllStatus();
        $arrtmp = explode("\\", PS_ADMIN_DIR);
        $adimDir = end($arrtmp);
        echo '
              <div class="tab-page" id="step1">
                <h4 class="tab">1. '.$this->l('Information.').'</h4>
                <link rel="stylesheet" type="text/css" href="'.__PS_BASE_URI__.'css/jquery.autocomplete.css" />
                        <script type="text/javascript" src="'.__PS_BASE_URI__.'js/jquery/jquery.autocomplete.js"></script>
                <form action="' . $currentIndex . '&submitAdd' . $this->table . '=1&token=' . $this->token . '" method="post"  enctype="multipart/form-data" autocomplete=off>
                ' . ($obj->id ? '<input type="hidden" name="id_' . $this->table . '" value="' . $obj->id . '" />' : '') . '
                <input type="hidden" name="tabs" id="tabs" value="0" />';
        if (!$obj->id)
        {
            echo '
                <label>Name - Email</label>
                <div class="margin-form">
                        <input id="zid_customer" name="id_customer" type="hidden" value="'.$this->getFieldValue($obj, 'id_customer').'">
                        <input id="email_customer" name="email_customer" type="hidden" value="'.$this->getFieldValue($obj, 'email_customer').'">
                        <input id="customerAuto" class="text" type="text" '.($obj->id ? 'disabled="disabled"' : '').' value="'.( $obj->id ? $this->getFieldValue($obj, 'name_customer').' ('.$this->getFieldValue($obj, 'email_customer').')' : '').'" size="37">
                        <sup> *</sup>
                        <p class="clear"></p>
                </div>		
         	';
        }  else {
             echo '
                <label>'.$this->l('Name - Email').'</label>
                <div style="font-size: 1em; margin-top: 3px;margin-left: 10px;float:left;">
                    '.$this->getFieldValue($obj, 'name_customer').' ('.$this->getFieldValue($obj, 'email_customer').')
                     <p class="clear">'.$this->l('').'</p>
                </div>
                <div class="clear"></div>';
        }
 ?>
<script type="text/javascript">
  function findValue(li) {
  	if( li == null ) return alert("No match!");

  	// if coming from an AJAX call, let's use the CityId as the value
  	if( !!li.extra ) var sValue = li.extra[0];

  	// otherwise, let's just display the value in the text box
  	else var sValue = li.selectValue;

  	//alert("The value you selected was: " + sValue);
  }

  function selectItem(li) {
    	findValue(li);
  }

    function formatItem(row) {
    	return row[1] +" - "+row[0];
    }

    function addEmailCustomer(event, row, formatted)
	{
		if (row == null)
			return false;
		
		var customerEmail = row[2];
		var customerId = row[1];
		$('#email_customer').val(customerEmail);
		$('#zid_customer').val(customerId);
                
                $.ajax({
			type: 'GET',
			async: true,
			cache: false,
			url: "../modules/zhelpdesk/ajax/ajax_order_list.php", 
			data:"customerId="+customerId, 
			success: function(data) {
                            if(data){
                                $('#zorderz').append(data);
                            }
                            else{
                                $('#zorderz').html('<option value="0">&nbsp;&nbsp; -- &nbsp;&nbsp;</option>');
                            }
			}
		});
                return false;
                
	}
    function getidcustom()
    {
        var ids = $('#zid_customer').val();
        return ids;

    }
    $(function() {    
       
        $("#customerAuto").autocomplete(
        //"ajax_customer_list.php",{
        '../modules/zhelpdesk/ajax/ajax_customer_list.php', {
                            minChars:1,
                            max:20,
                            matchSubset:1,
                            matchContains:true,
                            onItemSelect:selectItem,
                            onFindValue:findValue,
                            formatItem:formatItem,
                            autoFill:true
                    }
        ).result(addEmailCustomer);
       
    });
        
    
  
</script>
        <?php 
        if (!$obj->id)
        {
            echo '<label>'.$this->l('Assign to Order').'</label>
                    <div class="margin-form">
                        <select style="width:225px;" name="id_order" id="zorderz" >
                            <option value="0">&nbsp;&nbsp;'.$this->l('Please select order').'&nbsp;&nbsp;&nbsp;</option>
                        </select> 
                        <p class="clear">'.$this->l('').'</p>
                    </div>
                    <div class="clear"></div>';
        }  else {
            echo '<label>'.$this->l('Assign to Order').'</label>
                <div style="font-size: 1em; margin-top: 3px;margin-left: 10px;float:left;color: #268CCD;">
                    '.($this->getFieldValue($obj, 'id_order')!=0 ? '#0000'.$this->getFieldValue($obj, 'id_order') : '--').'
                     <p class="clear">'.$this->l('').'</p>
                </div>
                <div class="clear"></div>';
        }
        
        $objDepart= new ZDepartmentObject($obj->id_zhelpdesk_department);
        if ($cookie->id_employee == $objDepart->id_moderator OR $this->employee->id_profile == 1)
        {
        	echo $this->addElement('select', array ('label'=>'Assign To Department','name'=>'id_zhelpdesk_department','value0'=>'Please select department', 'values'=>$department, 'expand'=>'<sup> *</sup>', 'style'=>'width:225px;'));
        	echo $this->addElement('select', array ('label'=>'Priority','name'=>'id_zhelpdesk_ticket_priority', 'values'=>$priority, 'style'=>'width:225px;'));
        	echo $this->addElement('select', array ('label'=>'Status','name'=>'id_zhelpdesk_ticket_status', 'values'=>$status, 'style'=>'width:225px;'));
        }else{
        	echo $this->addElement('select', array ('label'=>'Assign To Department','name'=>'id_zhelpdesk_department','value0'=>'Please select department', 'values'=>$department, 'expand'=>'<sup> *</sup>', 'style'=>'width:225px;', 'disabled'=>true));
        	echo $this->addElement('select', array ('label'=>'Priority','name'=>'id_zhelpdesk_ticket_priority', 'values'=>$priority, 'style'=>'width:225px;', 'disabled'=>true));
        	echo $this->addElement('select', array ('label'=>'Status','name'=>'id_zhelpdesk_ticket_status', 'values'=>$status, 'style'=>'width:225px;', 'disabled'=>true));
        }
        // autocomplete select employee to staff
        echo '
        		<label>'.$this->l('Staff').' </label>
				<div class="margin-form">';
		// get mode by id	
		if (isset($obj->id))
			$employeeInContent = ZDepartmentObject::_getModeById($this->getFieldValue($obj, 'id_staff'));
		else 
			$employeeInContent = ZDepartmentObject::_getModeById(Tools::getValue('id_staff'));
		echo '
				<div id="divZTypeEmployee" style="font-size: 1.3em; margin: 3px 10px;float:left;color: #268CCD;font-weight: bold;">';
//		foreach ($employeeInContent as $employee)
			echo htmlentities($employeeInContent['firstname'].' '.$employeeInContent['lastname'], ENT_COMPAT, 'UTF-8').'<br />';
		echo '
				</div>
				<input type="hidden" name="id_staff" id="inputZTypeEmployee" value="';
//		foreach ($employeeInContent as $employee)
			echo (int)$employeeInContent['id_employee'];
		echo '" />
				<input type="hidden" name="nameZTypeEmployee" id="nameZTypeEmployee" value="';
//		foreach ($employeeInContent as $employee)
			echo $employeeInContent['firstname'].' '.$employeeInContent['lastname'];
	
		echo '" />

				<div id="ajax_choose_product" style="width:600px;">
					<p class="clear">'.$this->l('Begin typing the first letters of the lastname or firstname employee, then select the employee from the drop-down list:').'</p>
					<input type="text" value="" id="employee_autocomplete_input" size="35" />
				</div>
				<div class="clear">&nbsp;</div>';
?>
				<script type="text/javascript">
					urlToCall = null;
					/* function autocomplete */
					$(function() {
						$('#employee_autocomplete_input')
							.autocomplete( 
								'../modules/zhelpdesk/ajax/ajax_employee_list.php', {
								//'ajax_employee_list.php', {
								minChars: 1,
								autoFill: true,
								max:20,
								matchContains: true,
								mustMatch:true,
								scroll:false,
								cacheLength:0,
								formatItem: function(item) {
									return item[1]+' - '+item[0];
								}
							}).result(addZTypeEmployee);
						$('#employee_autocomplete_input').setOptions({
							extraParams: {excludeIds : getZemployeeIds()}
                                                        
						});
					});
					
					function getZemployeeIds()
					{
						var ids = '. $obj->id.'+',';
						ids += $('#inputZTypeEmployee').val().replace(/\-/g,',').replace(/\,$/,'');
						ids = ids.replace(/\,$/,'');
			
						return ids;
			
					}					
					function addZTypeEmployee(event, data, formatted)
					{
						if (data == null)
							return false;
						var productId = data[1];
						var productName = data[0];
					
						var $divZTypeEmployee = $('#divZTypeEmployee');
						var $inputZTypeEmployee = $('#inputZTypeEmployee');
						var $nameZTypeEmployee = $('#nameZTypeEmployee');
					
						/* delete product from select + add product line to the div, input_name, input_ids elements */
						$divZTypeEmployee.html(productName + '<br />');
						$nameZTypeEmployee.val(productName);
						$inputZTypeEmployee.val(productId);
						$('#employee_autocomplete_input').val('');
						$('#employee_autocomplete_input').setOptions({
							extraParams: {excludeIds : getZemployeeIds()}
						});
					}
					
					
					function delZTypeEmployee(id)
					{
						var div = getE('divZTypeEmployee');
						var input = getE('inputZTypeEmployee');
						var name = getE('nameZTypeEmployee');
					
						// Cut hidden fields in array
						var inputCut = input.value.split('-');
						var nameCut = name.value.split('¤');
					
						if (inputCut.length != nameCut.length)
							return alert('Bad size');
					
						// Reset all hidden fields
						input.value = '';
						name.value = '';
						div.innerHTML = '';
						for (i in inputCut)
						{
							// If empty, error, next
							if (!inputCut[i] || !nameCut[i])
								continue ;
					
							// Add to hidden fields no selected products OR add to select field selected product
							if (inputCut[i] != id)
							{
								input.value += inputCut[i] + '-';
								name.value += nameCut[i] + '¤';
								div.innerHTML += nameCut[i] + ' <br />';
							}
							else
								$('#selectAccessories').append('<option selected="selected" value="' + inputCut[i] + '-' + nameCut[i] + '">' + inputCut[i] + ' - ' + nameCut[i] + '</option>');
						}
					
						$('#employee_autocomplete_input').setOptions({
							extraParams: {excludeIds : getZemployeeIds()}
						});
					}
				</script>
<?php 	
		echo '
				</div>
				<div class="clear">&nbsp;</div>';
        // END autocomplete select employee to staff
        
        if (!$obj->id)
        {
            echo $this->addElement('text', array ('label'=>'Subject','name'=>'subject', 'disabled'=>true, 'expand'=>'<sup> *</sup>', 'more'=>'size="60"'));
            echo $this->addElement('file', array ('label'=>'Attach File','name'=>'attach', 'note'=>'This file exceeds the maximum size for attachments is 2MB'));
            echo $this->addElement('area', array ('label'=>'Content','name'=>'content', 'expand'=>'<sup> *</sup>'));
        }
        echo '
                <hr class="clear">
            	<div  style="text-align: center">
                    <input type="submit" value="' . $this->l('   Save   ') . '" name="submitAdd' . $this->table . '" class="button" />
                </div>
                <div class="small"><sup>*</sup> '.$this->l('Required field').'</div>
                </form>
        	</div>
           ';
        
	}
	/**
	 * 
	 * Display tab ticket Thread
	 * @param $obj ticket object
	 * 
	 * @return html
	 */
	public function displayContentTab($obj)
	{
		global $currentIndex,$cookie;
		echo '
            <div class="tab-page" id="step2">
                <h4 class="tab">2. '.$this->l('Ticket Thread .').'</h4>
                '.$this->l('Response ticket .').'
                <hr class="clear">
                <form action="' . $currentIndex . '&submitAdd' . $this->table . '=1&token=' . $this->token . '" method="post"  enctype="multipart/form-data" autocomplete=off>
                	' . ($obj->id ? '<input type="hidden" name="id_' . $this->table . '" value="' . $obj->id . '" />' : '') . '
                	<input type="hidden" name="tabs" id="tabs" value="0" />';
//		echo $this->addElement('text', array ('label'=>'Subject','name'=>'subject', 'disabled'=>true, 'expand'=>'<sup> *</sup>', 'more'=>'size="60"'));
                echo '
                    <label>'.$this->l('Subject').'</label>
                    <div style="font-size: 1em; margin-top: 1px;margin-left: 10px;float:left;font-weight: bold;">
                        <i>'.$this->getFieldValue($obj, 'subject').'</i>
                        <p class="clear">'.$this->l('').'</p>
                    </div>
                    <div class="clear"></div>';
                
                echo $this->addElement('file', array ('label'=>'Attach File','name'=>'attach', 'note'=>'This file exceeds the maximum size for attachments is 2MB'));
		echo $this->addElement('area', array ('label'=>'Content','name'=>'content', 'expand'=>'<sup> *</sup>'));
        echo '  
        			<hr class="clear">    
                	<div  style="text-align: center">
                    	<input type="submit" value="' . $this->l('   Reply   ') . '" name="submitReplyContent" class="button" />
                	</div>
                	<div class="small"><sup>*</sup> '.$this->l('Required field').'</div> 
                	<hr class="clear">
                </form>';
        // display list content
        echo $this->_displayListContent($obj);
        echo '
            </div>';
	}
	
	/**
	 * @see AdminTabs->display()
	 * 
	 * Manage page display (form, list...)
	 *
	 * @global string $currentIndex Current URL in order to keep current Tab
	 */
	function display()
	{
		global $currentIndex, $cookie;
		parent::display();
		echo $this->_getStyle($this->_list);
	}
	
    /**
     * @see admintab->afterAdd($obj) 
     * run code after add neww
     * @param object add new $obj
     */
	protected function afterAdd($obj){
		$objTicketContent = new ZTicketContentObject();
		
		$target = dirname(__FILE__).'/fileattach/';
		$file = $_FILES['attach']['name'];
		if($_FILES["attach"]["size"] <= 26214400)
		{
			if(move_uploaded_file($_FILES['attach']['tmp_name'],$target.$file)==true)
				$objTicketContent->attached_files = $file;
		}
		
		$objTicketContent->id_zhelpdesk_ticket = $obj->id;
//		$objTicketContent->id_staff = Tools::getValue('id_staff');
		$objTicketContent->content = Tools::getValue('content');
		if ($objTicketContent->add()){
			/*************** Send mail to staff when creat new ticket for staff  ***********************/
			$employee = new EmployeeCore($obj->id_staff);
			$department = new ZdepartmentObject($obj->id_zhelpdesk_department);
			$employee_moderator = new EmployeeCore($department->id_moderator);
			$textbody = Configuration::get('ASSIGNED_TICKET_TEMPLATE',Configuration::get('PS_LANG_DEFAULT'));
			if ($textbody == '')
				$textbody = '<p>Hi {name_staff}, you\'ve been assigned to a ticket to {name_moderator} processor</p><p>Ticket is sent from the client name {name_customer}, email {email_customer}</p><p>Subject {subject}</p><p>Please reply to this email within 24 hours</p>';
				
			$words = array (
				'{name_staff}' => $employee->firstname." ".$employee->lastname,
				'{name_moderator}' => $employee_moderator->firstname." ".$employee_moderator->lastname,
				'{name_customer}' => $obj->name_customer,
				'{email_customer}' => $obj->email_customer,
				'{subject}' => $obj->subject,
			);
			$rs = ZticketObject::sendMailTo ($employee->email,$employee->firstname,"Assigned: ".$obj->subject,$textbody,$words);
			/*************** Send mail to staff when creat new ticket for staff  ***********************/
			if ($rs)
				return true;
		}
		return false;

    }
    
    /**
     * @see admintab->afterAdd($obj) 
     * run code after add neww
     * @param object add new $obj
     */
	protected function afterUpdate($obj)
	{
		if (isset($_POST['change_staff'])) 
		{
			/*************** Send mail to staff when change staff ***********************/
			$employee = new EmployeeCore($_POST['id_staff']);
			$department = new ZdepartmentObject($obj->id_zhelpdesk_department);
			$employee_moderator = new EmployeeCore($department->id_moderator);
			$textbody = Configuration::get('ASSIGNED_TICKET_TEMPLATE',Configuration::get('PS_LANG_DEFAULT'));
			if ($textbody == '')
				$textbody = '<p>Hi {name_staff}, you\'ve been assigned to a ticket to {name_moderator} processor</p><p>Ticket is sent from the client name {name_customer}, email {email_customer}</p><p>Subject {subject}</p><p>Please reply to this email within 24 hours</p>';
				
			$words = array (
				'{name_staff}' => $employee->firstname." ".$employee->lastname,
				'{name_moderator}' => $employee_moderator->firstname." ".$employee_moderator->lastname,
				'{name_customer}' => $obj->name_customer,
				'{email_customer}' => $obj->email_customer,
				'{subject}' => $obj->subject,
			);
			$rs = ZticketObject::sendMailTo ($employee->email,$employee->firstname,"Assigned: ".$obj->subject,$textbody,$words);
			/*************** Send mail to staff ***********************/
			if ($rs)
				return true;
			else 
				return false;
		}
	}
    
    /**
     * 
     * show list ticket customer and staff
     * @param object $obj
     * 
     * @return html list content
     */
    public function _displayListContent($obj)
    {
    	global $cookie;
    	$arrContent = ZTicketObject::getContenTicket($obj->id);
    	if (is_array($arrContent) AND $arrContent){
    		foreach ($arrContent AS $content){
				echo '
				<table '.(isset($content['id_zhelpdesk_ticket_content']) ? ' id="'.$content['id_zhelpdesk_ticket_content'] : '').'"  class="table" cellpadding="0" cellspacing="0" style="width:100%;'.($content['content_staff']==0 ? 'border: 1px solid #8D8E8E;' : '').'">
					<thead>
						<tr class="nodrag nodrop">
					 ';
				if ($content['content_staff']==0){
					$objCustomer = new Customer();
					$customer = $objCustomer->getByEmail($content['email_customer']);
					if ($customer)
						echo '<th style="background:none;background-color:#A5B6BA;">'.Tools::displayDate($content['date_add'], (int)$cookie->id_lang, true). ' -- <a href="?tab=AdminCustomers&id_customer='.$customer->id.'&viewcustomer&token='.Tools::getAdminToken('AdminCustomers'.(int)(Tab::getIdFromClassName('AdminCustomers')).(int)($cookie->id_employee)).'">' .$content['name_customer']. ' ( '.$content['email_customer'].' )</a> ';
					else
						echo '<th style="background:none;background-color:#A5B6BA;">'.Tools::displayDate($content['date_add'], (int)$cookie->id_lang, true). ' -- ' .$content['name_customer']. ' ( '.$content['email_customer'].' ) '; 
				}else {
					$staff = new EmployeeCore($content['content_staff']);
					echo '<th>'.Tools::displayDate($content['date_add'], (int)$cookie->id_lang, true). ' -- <a href="?tab=AdminEmployees&id_employee='.$content['content_staff'].'&updateemployee&token='.Tools::getAdminToken('AdminEmployees'.(int)(Tab::getIdFromClassName('AdminEmployees')).(int)($cookie->id_employee)).'">' .$staff->firstname.' '.$staff->lastname. ' ( '.$staff->email.' ) </a>';
				}
				if (isset($content['id_zhelpdesk_ticket_rating']) AND $content['id_zhelpdesk_ticket_rating'])
				{
					echo '<span style="float:right;margin-right:10px;">'.$this->l('Raiting : ').ZratingObject::getRaitingById($content['id_zhelpdesk_ticket_rating']).'</span>';
				}
				
				echo '
							</th>
						</tr>
					</thead>';
				echo '
					<tr>
						<td style="font-size: 1.1em;">'.$content['content'].
				((isset($content['attached_files']) AND $content['attached_files']!='') ? '<span>'.$this->l('File attachment : ').'<a href="'._MODULE_DIR_.'zhelpdesk/fileattach/'.$content['attached_files'].'" taget="_blank"><img src="'._MODULE_DIR_.'/zhelpdesk/img/AdminAttachments.gif"> '.$content['attached_files'].'</a></span>' : '')
						.'</td>
					</tr>
				</table>
				<p class="clear"></p>
					';
				
    		}
    	}
    	
    }
    
    public function _getStyle($list)
    {
    	$rs= '
		<style type="text/css"> ';
		foreach ($list as $item) {
				$rs.='
					tr#tr_1_'.$item['id_zhelpdesk_ticket'].' td:nth-child(9)
					{
						background-color:'.$item['pri_bgcolor'].';
						color:'.$item['pri_text_color'].';
						text-align:center;
						font-weight: bold;
						border-radius: 6px;
					}';
				$rs.='
					tr#tr_1_'.$item['id_zhelpdesk_ticket'].' td:nth-child(10)
					{
						background-color:'.$item['stt_bgcolor'].';
						color:'.$item['stt_text_color'].';
						text-align:center;
						font-weight: bold;
						border-radius: 6px;
					}';
		}
		$rs.='	
			</style>';
		return $rs;
    }
    
    
}
	
